# -*- coding: utf-8 -*-
# @Time    : 2020/2/26 上午12:54
# @Author  : lilong
# @File    : observer_base_frame.py


class Observable():
    """被观察者：基类
    定义：私有变量、获得私有变量、设置私有变量、
    定义：实现继承类中update更新的方法
    """

    def __init__(self):
        self.__observers = []

    def addObserver(self, observer):
        self.__observers.append(observer)

    def removeObserver(self, observer):
        self.__observers.remove(observer)

    def notifyObservers(self):
        for ob in self.__observers:
            ob.update(self)     # 注意这里的self，传递的是Observable基类继承类的对象本身，是作为参数进行传递的


class Observer():
    """观察者：基类
       必须有一个更新的方法，继承类也必须实现这个方法
    """
    def update(self, waterheater):
        pass


class WaterHeater(Observable):
    """被观察者：热水器
       继承自基类的notifyObservers方法，主要"热水器"温度有所变化，就通知观察者
    """
    def __init__(self):
        super().__init__()
        self.__temperature = 25

    def getTemperature(self):
        return self.__temperature

    def setTemperature(self, temperature):
        self.__temperature = temperature
        print("current temperature is:", self.__temperature)
        self.notifyObservers()


class WashingMode(Observer):
    """观察者：该模式用于洗澡用"""
    def update(self, waterheater):
        if isinstance(waterheater, WaterHeater) \
            and waterheater.getTemperature() >= 50 \
            and waterheater.getTemperature() < 70:
            print("水已烧好，温度正好！可以用来洗澡了。")


class DrinkingMode(Observer):
    """观察者：该模式用于饮用"""
    def update(self, waterheater):
        if isinstance(waterheater, WaterHeater) and waterheater.getTemperature() >= 100:
            print("水已烧开！可以用来饮用了。")


def testWaterHeater():
    heater = WaterHeater()
    washingObser = WashingMode()
    drinkingObser = DrinkingMode()
    heater.addObserver(washingObser)
    heater.addObserver(drinkingObser)
    heater.setTemperature(40)
    heater.setTemperature(60)
    heater.setTemperature(100)



testWaterHeater()